<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-alert title="添加商品信息"
                      show-icon :closable="false" type="info"></el-alert>
            <!--            步骤条区域-->
            <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
                <el-step title="基本信息"></el-step> <!--activeIndex - 0隐性转化,将字符串转化成数字-->
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <!--            tabs标签页-->
            <el-form :model="addForm" :rules="addFormRules" label-width="100px" ref="addFormRef" label-position="top">
                <el-tabs tab-position="left" v-model="activeIndex"
                         @tab-click="tabClick" :before-leave="beforeTabsLeave">
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="addForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model="addForm.goods_price" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input v-model="addForm.goods_number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input v-model="addForm.goods_weight"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <el-cascader
                                    expandTrigger="hover"
                                    v-model="addForm.goods_cat"
                                    :options="cateList"
                                    :props="cateProps"
                                    @change="handleChange" clearable></el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="1">
                        <!--                        渲染表单的item项-->
                        <el-form-item v-for="(item,i) in manyData" :key="item.attr_id">
                            <!--                        复选框区域-->
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox :label="item1" v-for="(item1,i1) in item.attr_vals"
                                             :key="i1" border></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品属性" name="2">
                        <el-form-item :label="item2.attr_name" v-for="item2 in onlyData" :key="item2.attr_id">
                            <el-input v-model="item2.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品图片" name="3">
                        <!--   action表示图片要上传到后台的API地址   记得补全upload路径-->
                        <el-upload
                                action="https://lianghj.top:8888/api/private/v1/upload"
                                :on-preview="handlePreview"
                                :on-remove="handleRemove"
                                list-type="picture"
                                :headers="headersObj"
                                :on-success="handleSuccess">
                            <el-button size="small" type="primary">点击上传</el-button>
                            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <quill-editor
                                ref="myQuillEditor"
                                v-model="addForm.goods_say">
                            </quill-editor>
                        <el-button type="primary" class="addCate" @click="addCate">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>

        <el-dialog
                title="图片预览"
                :visible.sync="ViewdialogVisible"
                width="50%">
            <img :src="viewPath" alt="picture" class="Img">
        </el-dialog>
    </div>
</template>

<script>
    import  _ from  'lodash'
  export default {
    name: "add",
    data() {
      return {
        activeIndex: '0',
        addForm: {
          goods_name: '',
          goods_price: 0,
          goods_number: 0,
          goods_weight: 0,
          //商品所属的分类数组
          goods_cat: [],
          //上传图片的数组
          pic:[],
          //商品的详情描述
          goods_say:'',
          attrs:[],
        },
        addFormRules: {
          goods_name: [{required: true, message: '请输入用户名', trigger: 'blur'}],
          goods_price: [{required: true, message: '请输入商品价格', trigger: 'blur'}],
          goods_number: [{required: true, message: '请输入商品数量', trigger: 'blur'}],
          goods_weight: [{required: true, message: '请输入商品重量', trigger: 'blur'}],
          goods_cat: [{required: true, message: '请输入商品分类', trigger: 'blur'}],
        },
        cateList: [],
        cateProps: {
          //配置项
          label: 'cat_name',
          value: 'cat_id',
          children: 'children'
        },
        //商品动态参数
        manyData: [],
        onlyData: [],//商品静态属性
        //自定义上传图片的表格头
        headersObj:{
          //拿到token令牌
          Authorization: window.sessionStorage.getItem('token')
        },
        //预览图片的路径
        viewPath:'',
        ViewdialogVisible:false

      }
    },
    computed: {
      //所属三级分类ID
      cateId() {
        return this.addForm.goods_cat[2]
      }
    },
    methods: {
      //获取所有商品分类列表数据
      async getCateList() {
        const {data: res} = await this.$http.get(`categories`)
        if (res.meta.status !== 200) return this.$message.error('获取商品分类列表失败')
        this.cateList = res.data
        console.log(res.data)
      },
      //级联选择器值改变
      handleChange() {
        if (this.addForm.goods_cat.length !== 3) return this.addForm.goods_cat = []
        console.log(this.addForm)
      },
      //标签页跳转的切换
      beforeTabsLeave(activeName, oldActiveName) {
        //     console.log(activeName, oldActiveName)
        // return false //阻止标签的切换
        if (this.addForm.goods_cat.length !== 3 && oldActiveName == '0') {
          this.$message.error('请先选择商品分类')
          return false
        }
      },
      //标签点击
      async tabClick() {
        //证明访问的是动态参数标签页
        if (this.activeIndex === '1') {
          //获取所属商品的many参数
          const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {
            params: {
              sel: 'many'
            }
          })
          if (res.meta.status !== 200) return this.$message.error('获取动态参数失败')
          this.manyData = res.data
          //转化字符串为数组
          res.data.forEach(item => {
            item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
          })
        } else if (this.activeIndex === '2') {
          //获取商品的静态属性
          const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {
            params: {
              sel: 'only'
            }
          })
          if (res.meta.status !== 200) return this.$message.error('获取静态属性失败')
          this.onlyData = res.data
          console.log(this.onlyData);
        }
      },
      //点击图片   处理预览效果
      handlePreview(file) {
         console.log(file)
        // this.viewPath = file.response.data.url
        this.viewPath = file.url
        this.ViewdialogVisible =true
      },
      //处理移除图片的操作
      handleRemove(file) {
          //获取到flie中图片的临时路径
        const filePath = file.response.data.tmp_path
        //通过临时路径查找pic中对应的索引值
        const fileIndex = this.addForm.pic.findIndex( item =>{
         item.pic === filePath})
        //通过索引值在pic中调用splice删除
        this.addForm.pic.splice(fileIndex,1)
        console.log(this.addForm.pic);
      },
      //图片上次成功时返回
      handleSuccess(response){
        //拼接一个图片对象的信息
        const picInfo = { pic:response.data.tmp_path}
        //将拼接好的对象添加进图片数组
        this.addForm.pic.push(picInfo)
      },
      addCate(){
        console.log(this.addForm);
        //校验表单所有各项是否合格
        this.$refs.addFormRef.validate(async valid =>{
          if (!valid){this.$message.error('请正确填写每一项的值')}
          else{
          //发起添加商品的请求  需要深拷贝一份goods_cat变为字符串
          //lodash cloneDeep(obj)深拷贝
          const form = _.cloneDeep(this.addForm)
          form.goods_cat = form.goods_cat.join(',')
          //处理动态参数
          this.manyData.forEach( item =>{
            const newInfo = {
              attr_id: item.attr_id,
              attr_value:item.attr_vals.join(',')
            }
            this.addForm.attrs.push(newInfo)
          })
          //处理静态参数
          this.onlyData.forEach( item =>{
            const newInfo = {
              attr_id: item.attr_id,
              attr_value:item.attr_vals
            }
            this.addForm.attrs.push(newInfo)
          })
          form.attrs = this.addForm.attrs
          console.log(form)

          //发起添加商品的请求  商品名称要是唯一的
        const {data:res}= await this.$http.post(`goods`, form)
          if (res.meta.status !== 201 ) return this.$message.error('添加商品失败')
          this.$message.success('添加商品成功')
          this.$router.push('/goods')
          }
        })
      }
    },
    created() {
      this.getCateList()
    }
  }
</script>

<style scoped>
    .el-steps {
        margin: 15px 0;
        font-size: 12px;
    }

    .el-checkbox {
        margin: 10px 10px 5px 10px !important;
    }
    .Img{
        width: 100%;
    }
    .addCate{
        margin-top: 15px;
    }

</style>